package com.example.gulimallware.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.example.common.utils.R;
import com.example.gulimallware.entity.WmsPurchaseDetailEntity;
import com.example.gulimallware.entity.WmsWareSkuEntity;
import com.example.gulimallware.enums.PurchaseDetailStatusEnum;
import com.example.gulimallware.enums.PurchaseStatusEnum;
import com.example.gulimallware.feign.ProductFeignClient;
import com.example.gulimallware.service.WmsPurchaseDetailService;
import com.example.gulimallware.service.WmsWareSkuService;
import com.example.gulimallware.vo.MergeVo;
import com.example.gulimallware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimallware.dao.WmsPurchaseDao;
import com.example.gulimallware.entity.WmsPurchaseEntity;
import com.example.gulimallware.service.WmsPurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("wmsPurchaseService")
public class WmsPurchaseServiceImpl extends ServiceImpl<WmsPurchaseDao, WmsPurchaseEntity> implements WmsPurchaseService {
    @Autowired
    private WmsPurchaseDetailService wmsPurchaseDetailService;
    @Autowired
    private WmsWareSkuService wmsWareSkuService;
    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WmsPurchaseEntity> page = this.page(
                new Query<WmsPurchaseEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public R queryPageUnreceivePurchase() {
        List<WmsPurchaseEntity> list = lambdaQuery()
                .in(WmsPurchaseEntity::getStatus, PurchaseStatusEnum.CREATED.getCode(), PurchaseStatusEnum.ASSIGNED.getCode())
                .list();
        return R.ok().put("page", list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R merge(MergeVo mergeVo) {

        if(Objects.isNull(mergeVo.getPurchaseId())){
            //1.没有选择采购单，创建一个新单
            WmsPurchaseEntity wmsPurchaseEntity = new WmsPurchaseEntity();
            wmsPurchaseEntity.setStatus(PurchaseStatusEnum.CREATED.getCode());
            wmsPurchaseEntity.setCreateTime(new Date());
            wmsPurchaseEntity.setUpdateTime(new Date());
            this.save(wmsPurchaseEntity);
            mergeVo.setPurchaseId(wmsPurchaseEntity.getId());
        }
        if(CollectionUtil.isNotEmpty(mergeVo.getItems())){
            //2.合并采购单
            List<Long> items = mergeVo.getItems();
            List<WmsPurchaseDetailEntity> detailEntities = wmsPurchaseDetailService.listByIds(items);
            if(CollectionUtil.isEmpty(detailEntities)&&detailEntities.size()!=items.size()){
                return R.error("采购单不存在");
            }
            detailEntities.forEach(entity->{
                entity.setPurchaseId(mergeVo.getPurchaseId());
                entity.setStatus(PurchaseStatusEnum.ASSIGNED.getCode());
            });
            wmsPurchaseDetailService.updateBatchById(detailEntities);
        }
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R received(ArrayList<Long> ids) {

        List<WmsPurchaseEntity> list = ids.stream().map(this::getById).toList();
        if(list.size()!=ids.size()){
            return R.error("采购单不存在");
        }
        for (WmsPurchaseEntity wmsPurchaseEntity : list) {
            if(PurchaseStatusEnum.CREATED.getCode()!=wmsPurchaseEntity.getStatus()&&PurchaseStatusEnum.ASSIGNED.getCode()!=wmsPurchaseEntity.getStatus()){
                return R.error("采购单状态错误");
            }
        }
        //改变状态为已领取
        list.forEach(entity->{
            entity.setStatus(PurchaseStatusEnum.RECEIVE.getCode());
            entity.setUpdateTime(new Date());
        });
        updateBatchById(list);
        //改变采购项状态为正在采购
        List<WmsPurchaseDetailEntity> wmsPurchaseDetailEntities = wmsPurchaseDetailService.lambdaQuery().in(WmsPurchaseDetailEntity::getPurchaseId, ids).list();
        wmsPurchaseDetailEntities.forEach(entity-> entity.setStatus(PurchaseDetailStatusEnum.PURCHASING.getCode()));
        wmsPurchaseDetailService.updateBatchById(wmsPurchaseDetailEntities);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R done(PurchaseDoneVo purchaseDoneVo) {
        WmsPurchaseEntity purchaseEntity = getById(purchaseDoneVo.getId());
        if(Objects.isNull(purchaseEntity)){
            return R.error("采购单不存在");
        }
        if(PurchaseStatusEnum.RECEIVE.getCode()!=purchaseEntity.getStatus()){
            return R.error("采购单状态错误");
        }
        //改变采购项状态
        List<PurchaseDoneVo.PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<Long> itemIdList = items.stream().map(PurchaseDoneVo.PurchaseItemDoneVo::getItemId).toList();
        List<WmsPurchaseDetailEntity> wmsPurchaseDetailEntities = wmsPurchaseDetailService.listByIds(itemIdList);
        if(wmsPurchaseDetailEntities.size()!=itemIdList.size()){
            return R.error("采购项不存在");
        }
        boolean isFinished = true;
        List<WmsWareSkuEntity> wmsWareSkuEntities = new LinkedList<>();
        for (WmsPurchaseDetailEntity wmsPurchaseDetailEntity : wmsPurchaseDetailEntities) {
            if(PurchaseDetailStatusEnum.PURCHASING.getCode()!=wmsPurchaseDetailEntity.getStatus()){
                return R.error("采购项状态错误");
            }
            for (PurchaseDoneVo.PurchaseItemDoneVo item : items){
                if(wmsPurchaseDetailEntity.getId().equals(item.getItemId())){
                    wmsPurchaseDetailEntity.setStatus(item.getStatus());
                    if(item.getStatus()==PurchaseDetailStatusEnum.FAILED.getCode()){
                           isFinished=false;
                    }else{
                        //设置仓库sku信息
                        WmsWareSkuEntity wareSkuEntity = wmsWareSkuService.lambdaQuery()
                                .eq(WmsWareSkuEntity::getSkuId, wmsPurchaseDetailEntity.getSkuId())
                                .eq(WmsWareSkuEntity::getWareId, wmsPurchaseDetailEntity.getWareId())
                                .one();
                        if(Objects.isNull(wareSkuEntity)){
                            wareSkuEntity=new WmsWareSkuEntity();
                            wareSkuEntity.setSkuId(wmsPurchaseDetailEntity.getSkuId());
                            wareSkuEntity.setWareId(wmsPurchaseDetailEntity.getWareId());
                            wareSkuEntity.setStock(wmsPurchaseDetailEntity.getSkuNum());
                            String skuName = productFeignClient.getSkuName(wareSkuEntity.getSkuId());
                            if(Objects.isNull(skuName)){
                                return R.error("商品不存在");
                            }
                            wareSkuEntity.setSkuName(skuName);
                            wmsWareSkuEntities.add(wareSkuEntity);
                        }else{
                            wareSkuEntity.setStock(wareSkuEntity.getStock()+wmsPurchaseDetailEntity.getSkuNum());
                        }
                    }
                    break;
                }
            }
        }
        //改变采购单状态
        lambdaUpdate()
                .eq(WmsPurchaseEntity::getId, purchaseDoneVo.getId())
                .set(WmsPurchaseEntity::getStatus, isFinished?PurchaseStatusEnum.FINISH.getCode():PurchaseStatusEnum.HASERROR.getCode())
                .update();
        //改变采购项状态
        wmsPurchaseDetailService.updateBatchById(wmsPurchaseDetailEntities);
        //改变库存
        wmsWareSkuService.saveOrUpdateBatch(wmsWareSkuEntities);
        return R.ok();
    }

}